<script lang="ts" setup>
import { UserInfo } from '@/api/user/types';
import { updateUser } from '@/api/user';
import { VITE_APP_BASE_API } from '@/utils/base';
import { useUserStoreHook } from '@/store/modules/user';
import type { UploadProps } from 'element-plus'

const formRef = ref(ElForm);
const userStore = useUserStoreHook();

const upUrl = `http://120.78.138.37:8889/api/sys/upload/uploadFile?contentType=image/png`;
//const upUrl = `http://172.20.4.194:8888/api/sys/upload/uploadFile?contentType=image/png`;
const stateData = reactive({
  formData: {
    ...userStore.userInfo
  } as UserInfo,
  rules: {
    mobile: [
      {
        required: true,
        message: '手机号码非法',
        trigger: 'blur',
        pattern: /^1\d{10}$/
      }
    ],
    nickName: [{ required: true, message: '请输入账号昵称', trigger: 'blur' }],
    email: [
      {
        required: true,
        message: '请输入联系邮箱',
        trigger: 'blur',
        pattern: /^\w+@\w+\.[a-z]+$/i
      }
    ]
  },
  headers: {
    Authorization: userStore.token
  }
});
const { formData, rules, headers } = toRefs(stateData);

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  res: any
) => {
  console.log('头像=====', res)
  formData.value.avatar = res.data;
};

const beforeAvatarUpload = (rawFile: any) => {
  // rawFile.type === 'image/jpeg' ||
  if (rawFile.type === 'image/png') {
  } else {
    ElMessage.error('请上传png格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('大小不能超过2MB!');
    return false;
  }
  return true;
};

function handleError(err: any) {
  let myError = err.toString(); //转字符串
  myError = myError.replace('UploadAjaxError: ', ''); //去掉前面的
  myError = JSON.parse(myError); //转对象
  ElMessage.error(myError.msg);
}

async function handleSubmit() {
  await formRef.value.validate((valid: boolean, val: any) => {
    if (valid) {
      updateUser(formData.value)
        .then(async (res) => {
          userStore.getInfo()
          ElMessage.success('更新成功');
        })
        .catch(() => { });
    } else {
      return false;
    }
  });
}
</script>

<template>
  <div class="app-container">
    <div class="form-box">
      <div class="form-box-inner">
        <el-form class="form-class" ref="formRef" :model="formData" :rules="rules" label-width="120px"
          label-position="top" size="large">
          <el-row>
            <div class="upload-box">
              <div class="upload-inner">
                <el-upload class="avatar-uploader" :headers="headers" :action="upUrl" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-error="handleError">
                  <img v-if="formData.avatar" :src="`${$imageBaseUrl}${formData.avatar}`" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
                <div class="avatar-text">更换头像</div>
              </div>
            </div>
            <el-col>
              <el-form-item label="账号" prop="mobile">
                <el-input class="input-set" v-model.trim="formData.mobile" placeholder="请输入手机号码" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="昵称" prop="nickName">
                <el-input class="input-set" v-model.trim="formData.nickName" placeholder="请输入账号昵称" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="邮箱" prop="email">
                <el-input class="input-set" v-model.trim="formData.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-bottom">
            <div class="form-bottom-inner">
              <el-button class="sub-btn" type="primary" @click="handleSubmit">更新信息</el-button>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
 
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}

::v-deep .el-upload {
  border: 1px dashed #8c939d;
  cursor: pointer;
  position: relative;
  border-radius: 50%;
  overflow: hidden;
}

.form-class {
  .upload-box {
    display: flex;
    width: 100%;
    justify-content: center;
    margin-bottom: 40px;

    .upload-inner {
      .avatar-uploader {}

      .avatar-text {
        text-align: center;
        margin-top: 10px;
        color: #4379ee;
        // cursor: pointer;
      }
    }
  }
}
</style>
  